/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package kimo.persistence.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import kimo.persistence.entities.Producer;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import kimo.persistence.controllers.exceptions.IllegalOrphanException;
import kimo.persistence.controllers.exceptions.NonexistentEntityException;
import kimo.persistence.controllers.exceptions.PreexistingEntityException;
import kimo.persistence.entities.Daok;
import kimo.persistence.entities.User;

/**
 *
 * @author a381u296
 */
public class DaokJpaController implements Serializable {

    public DaokJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Daok daok) throws PreexistingEntityException, Exception {
        if (daok.getProducerList() == null) {
            daok.setProducerList(new ArrayList<Producer>());
        }
        if (daok.getUserList() == null) {
            daok.setUserList(new ArrayList<User>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Producer> attachedProducerList = new ArrayList<Producer>();
            for (Producer producerListProducerToAttach : daok.getProducerList()) {
                producerListProducerToAttach = em.getReference(producerListProducerToAttach.getClass(), producerListProducerToAttach.getProducerId());
                attachedProducerList.add(producerListProducerToAttach);
            }
            daok.setProducerList(attachedProducerList);
            List<User> attachedUserList = new ArrayList<User>();
            for (User userListUserToAttach : daok.getUserList()) {
                userListUserToAttach = em.getReference(userListUserToAttach.getClass(), userListUserToAttach.getUserId());
                attachedUserList.add(userListUserToAttach);
            }
            daok.setUserList(attachedUserList);
            em.persist(daok);
            for (Producer producerListProducer : daok.getProducerList()) {
                Daok oldProducerDaokCdOfProducerListProducer = producerListProducer.getProducerDaokCd();
                producerListProducer.setProducerDaokCd(daok);
                producerListProducer = em.merge(producerListProducer);
                if (oldProducerDaokCdOfProducerListProducer != null) {
                    oldProducerDaokCdOfProducerListProducer.getProducerList().remove(producerListProducer);
                    oldProducerDaokCdOfProducerListProducer = em.merge(oldProducerDaokCdOfProducerListProducer);
                }
            }
            for (User userListUser : daok.getUserList()) {
                Daok oldUserDaokCdOfUserListUser = userListUser.getUserDaokCd();
                userListUser.setUserDaokCd(daok);
                userListUser = em.merge(userListUser);
                if (oldUserDaokCdOfUserListUser != null) {
                    oldUserDaokCdOfUserListUser.getUserList().remove(userListUser);
                    oldUserDaokCdOfUserListUser = em.merge(oldUserDaokCdOfUserListUser);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findDaok(daok.getDaokCd()) != null) {
                throw new PreexistingEntityException("Daok " + daok + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Daok daok) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Daok persistentDaok = em.find(Daok.class, daok.getDaokCd());
            List<Producer> producerListOld = persistentDaok.getProducerList();
            List<Producer> producerListNew = daok.getProducerList();
            List<User> userListOld = persistentDaok.getUserList();
            List<User> userListNew = daok.getUserList();
            List<String> illegalOrphanMessages = null;
            for (Producer producerListOldProducer : producerListOld) {
                if (!producerListNew.contains(producerListOldProducer)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Producer " + producerListOldProducer + " since its producerDaokCd field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Producer> attachedProducerListNew = new ArrayList<Producer>();
            for (Producer producerListNewProducerToAttach : producerListNew) {
                producerListNewProducerToAttach = em.getReference(producerListNewProducerToAttach.getClass(), producerListNewProducerToAttach.getProducerId());
                attachedProducerListNew.add(producerListNewProducerToAttach);
            }
            producerListNew = attachedProducerListNew;
            daok.setProducerList(producerListNew);
            List<User> attachedUserListNew = new ArrayList<User>();
            for (User userListNewUserToAttach : userListNew) {
                userListNewUserToAttach = em.getReference(userListNewUserToAttach.getClass(), userListNewUserToAttach.getUserId());
                attachedUserListNew.add(userListNewUserToAttach);
            }
            userListNew = attachedUserListNew;
            daok.setUserList(userListNew);
            daok = em.merge(daok);
            for (Producer producerListNewProducer : producerListNew) {
                if (!producerListOld.contains(producerListNewProducer)) {
                    Daok oldProducerDaokCdOfProducerListNewProducer = producerListNewProducer.getProducerDaokCd();
                    producerListNewProducer.setProducerDaokCd(daok);
                    producerListNewProducer = em.merge(producerListNewProducer);
                    if (oldProducerDaokCdOfProducerListNewProducer != null && !oldProducerDaokCdOfProducerListNewProducer.equals(daok)) {
                        oldProducerDaokCdOfProducerListNewProducer.getProducerList().remove(producerListNewProducer);
                        oldProducerDaokCdOfProducerListNewProducer = em.merge(oldProducerDaokCdOfProducerListNewProducer);
                    }
                }
            }
            for (User userListOldUser : userListOld) {
                if (!userListNew.contains(userListOldUser)) {
                    userListOldUser.setUserDaokCd(null);
                    userListOldUser = em.merge(userListOldUser);
                }
            }
            for (User userListNewUser : userListNew) {
                if (!userListOld.contains(userListNewUser)) {
                    Daok oldUserDaokCdOfUserListNewUser = userListNewUser.getUserDaokCd();
                    userListNewUser.setUserDaokCd(daok);
                    userListNewUser = em.merge(userListNewUser);
                    if (oldUserDaokCdOfUserListNewUser != null && !oldUserDaokCdOfUserListNewUser.equals(daok)) {
                        oldUserDaokCdOfUserListNewUser.getUserList().remove(userListNewUser);
                        oldUserDaokCdOfUserListNewUser = em.merge(oldUserDaokCdOfUserListNewUser);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = daok.getDaokCd();
                if (findDaok(id) == null) {
                    throw new NonexistentEntityException("The daok with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Daok daok;
            try {
                daok = em.getReference(Daok.class, id);
                daok.getDaokCd();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The daok with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Producer> producerListOrphanCheck = daok.getProducerList();
            for (Producer producerListOrphanCheckProducer : producerListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Daok (" + daok + ") cannot be destroyed since the Producer " + producerListOrphanCheckProducer + " in its producerList field has a non-nullable producerDaokCd field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<User> userList = daok.getUserList();
            for (User userListUser : userList) {
                userListUser.setUserDaokCd(null);
                userListUser = em.merge(userListUser);
            }
            em.remove(daok);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Daok> findDaokEntities() {
        return findDaokEntities(true, -1, -1);
    }

    public List<Daok> findDaokEntities(int maxResults, int firstResult) {
        return findDaokEntities(false, maxResults, firstResult);
    }

    private List<Daok> findDaokEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Daok.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Daok findDaok(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Daok.class, id);
        } finally {
            em.close();
        }
    }

    public int getDaokCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Daok> rt = cq.from(Daok.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
